#!/usr/bin/env python
# -*- coding: utf8 -*-

import getopt, sys
from blogger import Blogger

class BloggerCli(object):
    def __init__(self):
        self.connect()
        self.select_blog()

    def create_post(self):
        title = raw_input('Введите заголовок: ')
        print 'Введите текст поста для завершения наберите c новой строки "end" и нажмите "Enter" '
        body = ''
        while True:
            row = raw_input()
            if 'end' == row.strip():
                break
            body += row + '\n'
        labels_raw = raw_input('Введите метки через запятую: ').strip()
        labels = None
        if labels_raw != '':
            labels = filter(lambda x: x.strip(), labels_raw.split(','))
        try:
            self.blog_client.create_post(title, body, labels, True, 'html')
        except Exception,e:
            if type(e.message) == dict:
                print e.message['body']
            else:
                print e.message

    def select_blog(self):
        blog_ids = []

        for indx, blogid in enumerate(self.blog_client.blogs):
            print "%d) %s" % (indx, self.blog_client.blogs[blogid]['title'])
            blog_ids.append(blogid)

        select_blogid = input('Выберите блог [0]: ')

        if select_blogid < len(blog_ids):
            self.blog_client.current_blogid = blog_ids[select_blogid]
        else:
            print "Не верный выбор"
            self.select_blog()

    def print_all_posts(self):
        posts = self.blog_client.get_all_posts()
        for indx, post in enumerate(posts):
            print "%d) %s (%s)" % (indx, post.title.text, ', '.join(label.term for label in post.category))

    def print_posts_by_labels(self):
        label = raw_input('Введите метку: ').strip()
        posts = self.blog_client.get_posts_by_label(label)
        for indx, post in enumerate(posts):
            print "%d) %s (%s)" % (indx, post.title.text, ', '.join(label.term for label in post.category))

    def delete_post(self):
        post_ids = raw_input('Введите номера постов через запятую: ')
        list_posts = filter(lambda x: x.strip(), post_ids.strip().split(','))
        posts = blog.get_all_posts()
        for num_post in list_posts:
            number = int(num_post)
            print "delete %d post" % number
            if number <= len(posts):
                self.blog_client.delete_post(posts[int(number)])

    def print_labels(self):
        print self.blog_client.get_labels()

    def usage(self):
        print __file__, '--email [email] --password [password]'

    def connect(self):
        try:
            opts, args = getopt.getopt(sys.argv[1:], "", ["email=", "password="])
        except getopt.error, msg:
            self.usage()
            sys.exit(2)

        email = ''
        password = ''

        # Process options
        for o, a in opts:
            if o == "--email":
                email = a
            elif o == "--password":
                password = a
            
        if email == '' or password == '':
            self.usage()
            sys.exit(2)
        
        self.blog_client = Blogger(email, password)

    def run(self):
        command = raw_input("Enter command: ").strip()
        while command != 'quit':
            if 'print-all-posts' == command:
                self.print_all_post()
            elif 'print-posts-by-labels' == command:
                self.print_posts_by_labels()
            elif 'delete' == command:
                self.delete()
            elif 'select-blog' == command:
                self.select_blog()
            elif 'create-post' == command:
                self.create_post()
            elif 'print-labels' == command:
                self.print_labels()
            elif 'help' == command:
                self.help()
            else:
                print 'Не верная команда'

            command = raw_input("Enter command: ")

    def help(self):
        print '''\
        print-all-posts         напечатать все посты
        create-post             создать пост
        delete                  удалить пост
        print-posts-by-labels   найти посты по тегам
        select-blog             выбрать блог
        print-labels            напечатать все теги
        help                    вывести справку
        quit                    выход
        '''


if __name__ == '__main__':
    bcli = BloggerCli()
    bcli.run()
